package cn.gp.controller;

import cn.gp.common.R;
import cn.gp.dto.UserDto;
import cn.gp.entity.User;
import cn.gp.service.UserService;
import cn.gp.util.JwtUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author He_Guoping
 * @Date 2023/5/24 12:54
 * @Version 1.0
 */
@Log4j
@RestController
@RequestMapping("/users")
//@CrossOrigin("*")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     *@Description 用户登陆
     *@param user
     *@Return cn.gp.common.R<cn.gp.dto.UserDto>
     *@Author He_Guoping
     *@Date 09:25 2023/5/26
     */
    @PostMapping("/login")
    public R<UserDto> login(@RequestBody User user) {
        log.info("user: " + user);

        UserDto userDto = new UserDto();
        User u = userService.login(user);

        if(u != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("username", u.getUsername());
            String token = JwtUtils.generateToken(map, (long) 3600 * 1000);
            userDto.setToken(token);
            BeanUtils.copyProperties(user, userDto,"password");
            return R.success(userDto);
        }

        return R.error("登陆失败");
    }
}
